﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Navigation;

namespace Microsoft.Phone.Controls
{
    /// <summary>
    /// Controls Extensions.
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// Removes <see cref="JournalEntry">JournalEntries</see> from navigation journal of provided <see cref="PhoneApplicationFrame">frame</see> until <paramref name="stopCondition"/> is not true.
        /// </summary>
        /// <param name="frame"><see cref="PhoneApplicationFrame">Frame</see>.</param>
        /// <param name="stopCondition">Condition.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void RemoveBackStackEntriesWhile(
            this PhoneApplicationFrame frame, 
            Func<JournalEntry, bool> stopCondition)
        {
            if (frame == null)
            {
                return;
            }

            if (stopCondition == null)
            {
                throw new ArgumentNullException("stopCondition");
            }

            while (frame.BackStack.Any()
                   && (frame.BackStack is Stack<JournalEntry>
                       && !stopCondition((frame.BackStack as Stack<JournalEntry>).Peek())))
            {
                frame.RemoveBackEntry();
            }
        }

        /// <summary>
        /// Removes <see cref="JournalEntry">JournalEntries</see> from navigation journal of provided <see cref="PhoneApplicationFrame">frame</see> leaving predefined count.
        /// </summary>
        /// <param name="frame"><see cref="PhoneApplicationFrame">Frame</see>.</param>
        /// <param name="leaveCount">Number of entries to leave.</param>
        public static void RemoveBackStackEntries(
            this PhoneApplicationFrame frame, 
            int leaveCount = 0)
        {
            if (frame == null)
            {
                return;
            }

            if (leaveCount < 0)
            {
                throw new InvalidOperationException();
            }

            while (frame.BackStack.Any())
            {
                if (frame.BackStack.Count() <= leaveCount)
                {
                    break;
                }

                frame.RemoveBackEntry();
            }
        }
    }
}
